﻿namespace NFox.Pycad.Core.Modules
{
    public class lisp
    {

        public string Name { get; protected set; }

        public bool Lock { get; protected set; }

        protected dynamic _func;

        public lisp(string name = null, bool @lock = true)
        {
            Name = name;
            Lock = @lock;
        }

        public dynamic __call__(dynamic args = null)
        {
            if (Application.GetValue("callable")(args))
            {
                if (Name == null) Name = args.__name__;
                _func = args;
                pye.addlisp(this);
                return this;
            }
            else
            {
                var ed = Application.GetValue("ed");
                ed();
                var stdio = Application.GetValue("stdio");
                var console = stdio.console;
                dynamic res = null;
                try
                {
                    stdio.redirect(null);
                    using (new lockdoc(ed.Document))
                        res = conv.ToLispData(_func(conv.FromLispData(args)));
                }
                finally
                {
                    stdio.redirect(console);
                }
                return res;
            }
        }


    }
}
